import dayjs from 'dayjs'

export function useTable(remoteApi) {
  let loading = ref(true)
  let tableData = ref([])
  let total = ref(0)
  let totalOption = ref([10, 20, 30, 40, 50, 100])

  let params = ref({
    page: 1,
    per_page: 10,
  })
  let selectData = ref([])

  onMounted(() => {
    getTableData(params.value)
  })

  const search = () => {
    params.value.page = 1
    getTableData(params.value)
  }

  const getTableData = async query => {
    if (!remoteApi) return
    loading.value = true
    const { code, data, msg } = await remoteApi({ ...query })
    tableData.value = data.data
    total.value = data.total
    params.value.page = +data.current_page
    params.value.per_page = +data.per_page
    !totalOption.value.includes(params.value.per_page) &&
      totalOption.value.unshift(params.value.per_page)
    tableData.value.forEach(item => {
      item.created_at = dayjs(item.created_at).format('YYYY-MM-DD HH:mm')
    })
    loading.value = false
  }

  const resetTableData = () => {
    getTableData()
  }

  const selectChange = row => (selectData.value = row)

  const handleDelete = async deleteApi => {
    const ids = selectData.value.map(item => item.id)
    const { code } = await deleteApi(ids)
    if (code === 200) {
      ElMessage.success('删除成功')
      await getTableData()
    }
  }

  const handleTotal = val => {
    params.value.per_page = val
  }

  /**
   * watch page change load table data
   */
  watch(
    () => params.value.page,
    () => {
      getTableData(params.value)
    }
  )

  return {
    params,
    search,
    getTableData,
    resetTableData,
    handleDelete,
    selectChange,
    tableData,
    total,
    totalOption,
    handleTotal,
    loading,
  }
}
